<template>
  <div class="userinfo">
    <el-form :inline="true">
      <el-form-item label="征地项目：">
        <el-select v-model="value" value-key="Id" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.Id"
            :label="
              item.township +
              '--' +
              item.Village +
              '--' +
              item.YearNum +
              '--' +
              item.ProjectName
            "
            :value="item.Id"
            :visible-change="overChange()"
          />
        </el-select>
        <span @click="switchss">
          <el-button v-if="condition" class="el-icon-caret-top"
            >项目详情</el-button
          >
          <el-button v-else class="el-icon-caret-bottom">项目详情</el-button>
        </span>

        <!-- 功能按钮 -->

        <el-button
          class="el-icon-circle-plus-outline"
          @click="dialogTableVisible = true"
          >导入文件</el-button
        >
        <el-button class="el-icon-edit-outline" @click="determine"
          >确认保存</el-button
        >
        <a
          href="http://39.106.119.158:9000/uploadfile/被征地农民信息导入模板.xlsx"
          ><el-button class="el-icon-download">下载模板</el-button></a
        >
        <el-button class="el-icon-delete" @click="clear()">清除内容</el-button>
      </el-form-item>
    </el-form>

    <!-- 征地项目详情页 -->
    <div class="xiang">
      <el-table
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        v-show="condition"
        :data="tableData"
        border
        style="width: 1991px"
        height="97"
      >
        <el-table-column prop="township" label="乡镇" width="130" />
        <el-table-column prop="Village" label="村" width="180" />
        <el-table-column prop="ProjectName" label="用地项目名称" width="220" />
        <el-table-column prop="YearNum" label="年度" width="130" />
        <el-table-column prop="BatchNum" label="批次" width="130" />
        <el-table-column prop="BlockNum" label="地块" />
        <el-table-column prop="ApprovedDate" label="基准日期" width="180">
          <template slot-scope="scope">{{
            formatDate(scope.row.ApprovedDate)
          }}</template>
        </el-table-column>
        <el-table-column
          prop="ApprovedArea"
          label="用地面积（亩）"
          width="150"
        />
        <el-table-column prop="RegionPrice" label="区片价（元）" width="160" />
        <el-table-column prop="LevyScale" label="征缴比例">
          <template slot-scope="scope">{{
            (scope.row.LevyScale * 100).toFixed(2) + "%"
          }}</template>
        </el-table-column>
        <el-table-column
          prop="SecurityAmount"
          label="社会保险费（元）"
          width="150"
        />
      </el-table>
    </div>

    <!-- 文件上传 -->
    <el-dialog title="文件上传" :visible.sync="dialogTableVisible">
      <el-upload
        class="upload-demo"
        :auto-upload="false"
        :http-request="uploadSectionFile"
        action=""
        drag
        name="txt_file"
        :limit="1"
        :file-list="fileList"
        :multiple="false"
        :on-change="importExcel"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
      >
        <!-- 
        
        <el-dialog title="文件上传" :visible.sync="dialogTableVisible">
      <el-upload
        class="upload-demo"
        :auto-upload="false"
        :http-request="uploadSectionFile"
        action="http://39.106.119.158:9000/farmer/UploadExcelFile"
        :on-success="
          (res) => {
            this.importExcel();
            this.fileList = [];
            this.dialogTableVisible = false;
          }
        "
        :on-error="
          (err) => {
            this.fileList = [];
          }
        "
        drag
        name="txt_file"
        :limit="1"
        :file-list="fileList"
        :multiple="false"
        :on-change="importExcel"
      >
 -->
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">上传文件大小不超过4Mb</div>
      </el-upload>
    </el-dialog>

    <!-- 上传文件展示列表 -->
    <el-table
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
      :data="
        tableList.slice((currentPage - 1) * pagesize, currentPage * pagesize)
      "
      border
      style="width: 2021px"
      height="100vh - 204px"
    >
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="ListError[0][error]" label="提示" width="300" />
      <el-table-column prop="SocialSecurityType" label="参保类型" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.SocialSecurityType == 0">其他</span>
          <span v-else-if="scope.row.SocialSecurityType == 1">城居保</span>
          <span v-else>职保</span>
        </template>
      </el-table-column>
      <el-table-column prop="Name" label="姓名" width="110" />
      <el-table-column prop="Gender" label="性别" width="100">
      </el-table-column>
      <el-table-column prop="IdentityNum" label="身份证号" width="180" />
      <el-table-column
        prop="PovertySubsidyYears"
        label="享受困难补贴年限（月）"
        width="115"
      />
      <el-table-column
        prop="CompanyPaymentYears"
        label="职工养老缴费年限（月）"
        width="115"
      />
      <el-table-column prop="SocialSecurityNum" label="社保卡号" width="180" />
      <el-table-column prop="BankName" label="开户行名称" width="180" />
      <el-table-column prop="BankAccount" label="银行账号" width="200" />
      <el-table-column
        prop="SocialSecurityTypeOriginal"
        label="原有社保类型"
        width="180"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.SocialSecurityTypeOriginal == 0">无</span>
          <span v-else-if="scope.row.SocialSecurityTypeOriginal == 1"
            >城居保</span
          >
          <span v-else>职保</span>
        </template>
      </el-table-column>
      <el-table-column prop="PaymentStatus" label="社保缴费状态" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.PaymentStatus == 0">无</span>
          <span v-else-if="scope.row.PaymentStatus == 1">缴费</span>
          <span v-else>享受待遇</span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 50, 100, 200]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="this.tableList.length"
    >
    </el-pagination>
  </div>
</template>

<script>
import {
  API_GET_LAND,
  API_GET_BYID,
  API_CREATE_FARMER,
  API_MUBAN_DOWN,
  API_UPLOAD_EXCEL,
} from "../../api/table";
import XLSX from "xlsx";
export default {
  name: "",
  data() {
    return {
      msg: "人员信息导入",
      pagesize: 10, //每页的数据条数
      currentPage: 1,
      /* 征地项目名称 */
      options: [],
      value: "",
      val: "",
      condition: false,
      dialogTableVisible: false, // 文件上传显示隐藏
      tableData: [],
      tableList: [],
      /* 上传文件列表 */
      fileList: [],
    };
  },
  created() {
    this.submitProjectName();
  },
  methods: {
    switchss() {
      // 是否已经选择征地项目
      if (this.value != "") {
        // 项目详情是否已经展示
        this.submitId();
        this.condition = !this.condition;
      } else {
        this.$message.warning("请选择征地项目");
        this.condition = false;
      }
      console.log(this.value);
    },
    uploadSectionFile() {
      //file就是当前添加的文件
      var fileObj = param.file; // FormData 对象
      var form = new FormData(); // 文件对象,key是后台接受的参数名称
      form.append("uploadFile", fileObj);
      API_UPLOAD_EXCEL(form).then((res) => {
        // 这里做上传后的操作
        this.$message.success("成功！");
      });
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pagesize = val;
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
    },

    // 拼音排序
    // compareFunction(param1, param2) {
    //   console.log(params1,params2);
    //   return param1.localeCompare(param2, "zh");
    // },

    /* 导出文档 */
    exportClick() {
      // this.export2Excel();
      API_MUBAN_DOWN()
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    export2Excel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require("../../vendor/Export2Excel");

        const tHeader = [
          "姓名",
          "身份证号",
          "社保卡号",
          "享受困难补贴年限（月）",
          "职工养老缴费年限（月）",
          "参保类型",
        ];

        const filterVal = [
          "landname",
          "batch",
          "massif",
          "measureland",
          "areaprice",
          "levytaxes",
        ];

        const list = [];

        const data = this.formatJson(filterVal, list);

        export_json_to_excel(tHeader, data, "test");
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    printText() {
      this.$router.push("/projectinfo/print");
    },
    /* 上传文件 */
    beforeAvatarUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "xls";
      const extension2 = testmsg === "xlsx";
      const isLt2M = file.size / 1024 / 1024 < 4;
      if (!extension && !extension2) {
        this.$message({
          message: "上传文件只能是 xls、xlsx格式!",
          type: "warning",
        });
      }
      if (!isLt2M) {
        this.$message({
          message: "上传文件大小不能超过 4MB!",
          type: "warning",
        });
      }
      return extension || (extension2 && isLt2M);
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      console.log(file);
    },
    importExcel(file, fileList) {
      // console.log(param);
      this.fileList = fileList;
      this.file2Xce(file);
    },
    file2Xce(file) {
      let formData = new FormData();
      file.name = "txt_file";
      let data = {
        txt_file: file,
      };
      this.fileList.forEach((item) => {
        formData.append("txt_file", item.raw);
        // console.log(item);
      });
      data.txt_file = formData;
      console.log(data);
      // this.axios.post(api, formData);
      API_UPLOAD_EXCEL(formData)
        .then((res) => {
          console.log(res);
          this.tableList = res.ResList;
          this.dialogTableVisible = false;
        })
        .catch((err) => {
          this.fileList = [];
        });
    },
    allUpload() {
      console.log("占个位");
    },
    /* 性别渲染 */
    filterTag(value, row) {
      return row.tag === value;
    },

    /* 时间戳格式化 */
    formatDate(time) {
      if (time != "") {
        let aaa = parseInt(time.toString().substr(6, 13));
        if (aaa > 0) {
          return new Date(aaa).toLocaleDateString();
        } else {
          return "--";
        }
      }
    },

    /* 获取征地项目列表 */
    submitProjectName() {
      API_GET_LAND()
        .then((res) => {
          this.options = res.ResList;
          // res.ResList.map((item,index) => {
          //   // console.log(this.options.sort(this.compareFunction(item[index],item[index + 1])));
          // });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    /* 获取征地项目详情信息 */
    submitId() {
      this.val = this.value;
      let data = {
        lid: this.val,
      };
      API_GET_BYID(data)
        .then((res) => {
          console.log(res);
          this.tableData = res.ResList;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    overChange() {
      if (this.value != this.val) {
        // this.condition = false;
        let data = {
          lid: this.value,
        };
        API_GET_BYID(data)
          .then((res) => {
            console.log(res);
            this.tableData = res.ResList;
            this.val = this.value;
          })
          .catch((err) => {
            console.log(err);
          });
      }
    },
    clear() {
      this.fileList = [];
      this.tableList = [];
    },
    // 确定保存
    determine() {
      console.log(this.fileList);
      if (this.value != "" && this.tableList.length != 0) {
        let data = {
          // FileName: "test.xlsx",
          FileName: this.fileList[0].raw.name,
          landid: this.value,
        };
        console.log(data);
        API_CREATE_FARMER(data)
          .then((res) => {
            console.log(res);
            this.fileList = [];
            this.tableList = [];
            this.$message({
              type: "success",
              message: "数据导入成功！",
            });
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.$message.warning("选择征地项目、导入文件后才可保存！！！");
      }
    },
  },
};
</script>

<style scoped lang="scss">
.userinfo {
  padding: 30px;
  .el-button {
    margin-left: 10px;
  }
  .el-table {
    margin-top: 10px;
    height: calc(100vh - 345px);
    .cell {
      text-align: center;
    }
  }
  .el-dialog__header {
    text-align: center;
  }
  .upload-demo {
    text-align: center;
    .el-dialog__title {
      margin: 0 auto;
    }
  }
  .el-pagination {
    max-width: 1991px;
    margin-top: 10px;
    text-align: right;
  }
  .xiang {
    ::v-deep .el-table__body-wrapper {
      height: 48px !important;
    }
  }
}
</style>
